package ct.zxd.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ct.zxd.db.Dao;

public class HandleCategory extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			
		response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;character=utf-8");  
        response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("utf-8");
			
		PrintWriter writer = response.getWriter();
		
			String show = request.getParameter("showid");
			String title = request.getParameter("title");
			String flag = request.getParameter("flag");
			String shop = request.getParameter("shop");
			String cateid = shop+show;
			
				try {
					Dao dao = new Dao();
					int count = 0;
					String html = "<script language=\"javascript\">parent.location.href='category.jsp?shopid="+shop+"';</script>";
					
					if(flag.equals("del")){
						count = dao.deleteCategory(cateid);
					}else{
						if(dao.isExisted("category", shop, title,show)){
							request.setAttribute("err", title+" 已存在，请重新输入");
							request.getRequestDispatcher("addcategory.jsp?shop="+shop+"&flag="+flag+"&show="+show).forward(request, response);   
						}else{
							if(flag.equals("update")){
								count = dao.updateCategory(cateid, title);
							}else{
								 count = dao.insertCategory(title, cateid, shop, show);
							}
						}
					}
					
					if(count>0){
						writer.write(html);
					}else{
						writer.write("数据库出错");
					}
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					System.out.println(e);
					if(flag.equals("del")) {
						writer.write("数据库出错，请检查分类下是否还有商品");
					}else {
						writer.write("服务器连接错误");
					}
				}
			}
	

}
